package com.leyou.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.controller.UploadController;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    //支持文件的类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

    public String upload(MultipartFile file){
        try{
            //1.图片信息校验
            //1)校验文件类型
            String type = file.getContentType();

            if(!suffixes.contains(type)){
                logger.info("文件上传失败,类型不匹配:{}"+type);
                return null;
            }
            //2)校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());

            if(image==null){
                logger.info("文件上传失败,内容不符合要求");
                return null;
            }
            //2.保存图片
            //2.1 获取文件后缀名
            String s = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

            //2.2 上传
            StorePath storePath = this.fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), s, null);

            return "http://47.100.198.18/"+storePath.getFullPath();

        }catch (Exception e){
                return null;
        }
    }

}
